package com.ymh.service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by aivin on 2018/7/25.
 */
public class SaleTicketService {

    private Integer count = 100;//总的火车票数量

    private Lock lock = new ReentrantLock();//Lock加锁

    //销售车票的方法
    public  void sale() throws InterruptedException {
        TicketRunnable tr = new TicketRunnable();
        Thread t1 = new Thread(tr,"窗口A");
        Thread t2 = new Thread(tr,"窗口B");
        Thread t3 = new Thread(tr,"窗口C");
        Thread t4 = new Thread(tr,"窗口D");

        t1.start();
        t2.start();
        t3.start();
        t4.start();

        //主线程等待子线程执行完毕
        Thread.currentThread().join();
    }

    public  class TicketRunnable implements Runnable {
        @Override
        public void run() {

            while (count > 0) {
//                synchronized (count) { //synchronized加锁
                lock.lock(); //阻塞式加锁，一直到加上为止
                try {
                    if (count > 0) {
                        System.out.println(Thread.currentThread().getName()
                                + "售出第" + (count--) + "张票");
                    }
                }finally {
                    lock.unlock();//Lock加锁时需要在finally块中解锁，防止出现死锁
                }
//                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
